package com.mars.nacos.predicate;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Author: kyrie  @date: 2023/2/1 13:53
 * @Description: 自定义年龄段断言工厂
 * @Package: com.mars.nacos.predicate
 * @Email: wuxiang@roowoo.cn
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {


    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }

    /**
     * 用于从配置文件中获取参数值赋值到配置类中的属性上
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minAge", "maxAge");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return (GatewayPredicate) serverWebExchange -> {
            String age = serverWebExchange.getRequest().getQueryParams().getFirst("age");
            if (StringUtils.isNotEmpty(age)) {
                int ageInt = Integer.parseInt(age);
                return ageInt >= config.getMinAge() && ageInt <= config.getMaxAge();
            }
            return true;
        };
    }

    @Validated
    @Data
    public static class Config {
        /**
         * 最小年龄
         */
        private int minAge;
        /**
         * 最大年龄
         */
        private int maxAge;
    }
}
